function randomString(len) {
    len = len || 32;
    var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; 
    var maxPos = $chars.length;
    var ranstr = '';
    for (i = 0; i < len; i++) {
        ranstr += $chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return ranstr;
}

var wait = 60;
function calEmailTime(obj) {
    if (wait == 0) {
        $(obj).removeClass("layui-btn-disabled").addClass("layui-btn-primary");
        $(obj).text("获取验证码");
        wait = 60;
    } else { 
        $(obj).text(wait+'秒后重发');
        wait--;
        setTimeout(function(){calEmailTime(obj);}, 1000);
    }
}

function calMobileTime(obj) {
    if (wait == 0) {
        $(obj).removeClass("layui-btn-disabled").addClass("layui-btn-primary");
        $(obj).text("获取验证码");
        wait = 60;
    } else { 
        $(obj).text(wait+'秒后重发');
        wait--;
        setTimeout(function(){calMobileTime(obj);}, 1000)
    }
}

function getEmailResetVcode(btnObj) {
    $(btnObj).removeClass("layui-btn-primary").addClass("layui-btn-disabled");
    var email_num = $('#resetemail').val();
    if(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email_num)){
        $.ajax({
            type : 'GET',
            async : false,
            contentType : 'application/json; charset=utf-8',
            cache : false,
            url : 'validatecode/resetpwdbyemailcode',
            dataType : 'json',
            data : {'email_num' : email_num},
            success:function(data){
                if (data.code==0) {
                    calEmailTime(btnObj);
                }else{
                     $('div.tip-box').text(data.msg);
                }
            }
        });
    } else {
       $('div.tip-box').text("请输入正确格式的电子邮箱！");
    }
}

function getMobileResetVcode(btnObj) {
    $(btnObj).removeClass("layui-btn-primary").addClass("layui-btn-disabled");
    var mobile_num = $('#resetmobile').val();
    if(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(mobile_num)){
        $.ajax({
            type : 'GET',
            async : false,
            contentType : 'application/json; charset=utf-8',
            cache : false,
            url : 'validatecode/resetpwdbymobilecode',
            dataType : 'json',
            data : {'mobile_num' : mobile_num},
            success:function(data){
                if (data.code==0) {
                    calMobileTime(btnObj);
                }else{
                     $('div.tip-box').text(data.msg);
                     return false;
                }
            }
        });
    } else {
        $('div.tip-box').text("请输入正确格式的手机号码！");
    }
}

function getMobileRegistVcode(btnObj) {
    $(btnObj).removeClass("layui-btn-primary").addClass("layui-btn-disabled");
    var mobile_num = $('#registmobile').val();
    if(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(mobile_num)){
        $.ajax({
            type : 'GET',
            async : false,
            contentType : 'application/json; charset=utf-8',
            cache : false,
            url : 'validatecode/registermobilecode',
            dataType : 'json',
            data : {'mobile_num' : mobile_num},
            success:function(data){
                if (data.code==0) {
                    calMobileTime(btnObj);
                }else{
                     $('div.tip-box').text(data.msg);
                     return false;
                }
            }
        });
    } else {
        $('div.tip-box').text("请输入正确格式的手机号码！");
    }
}

$(document).keydown(function (e) {
    var event = document.all ? window.event : e;
    if (event.keyCode === 13) {
        $("input[type='button']").click();
    }
});

$(function(){

    $('#vcImg').attr('src','validatecode?randomStr='+randomString(6));
    $('div.beg-remember').on('click', function(){$('.dropdown-menu').toggle(); });
    
    layui.use(['layer', 'form'], function() {
        var layer = layui.layer,
            form = layui.form,
            $ = layui.jquery;
            
        $("#resetemail").on("input propertychange", function(){
            var email_num = $(this).val();
            var btnObj = $("#js_vcode");
            if(/^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/.test(email_num)){
                btnObj.removeClass("layui-btn-disabled").addClass("layui-btn-primary");
                btnObj.attr("onclick", "getEmailResetVcode(this)");
            }else{
                btnObj.removeClass("layui-btn-primary").addClass("layui-btn-disabled");
                btnObj.attr("onclick", "");
            }
        });
        
        $("#resetmobile").on("input propertychange", function(){
            var mobile_num = $(this).val();
            var btnObj = $("#js_vcode");
            if(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(mobile_num)){
                btnObj.removeClass("layui-btn-disabled").addClass("layui-btn-primary");
                btnObj.attr("onclick", "getMobileResetVcode(this)");
            }else{
                btnObj.removeClass("layui-btn-primary").addClass("layui-btn-disabled");
                btnObj.attr("onclick", "");
            }
        });
        
        $("#registmobile").on("input propertychange", function(){
            var mobile_num = $(this).val();
            var btnObj = $("#js_vcode");
            if(/^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\d{8}$/.test(mobile_num)){
                btnObj.removeClass("layui-btn-disabled").addClass("layui-btn-primary");
                btnObj.attr("onclick", "getMobileRegistVcode(this)");
            }else{
                btnObj.removeClass("layui-btn-primary").addClass("layui-btn-disabled");
                btnObj.attr("onclick", "");
            }
        });
        
        $("#validatecode").on("input propertychange", function(){
            var vcode = $(this).val();
            var btnObj = $("#js_submit");
            if(vcode!="" && vcode.length==6){
                btnObj.removeClass("layui-btn-disabled").addClass("layui-btn-normal");
                btnObj.removeAttr('disabled');
            }else{
                btnObj.removeClass("layui-btn-normal").addClass("layui-btn-disabled");
                btnObj.prop('disabled','disabled');
            }
        });
        
        $("input[name='username']").focus();
        form.on('submit(login)',function(data){
            var btnObj = $(this);
            btnObj.val("正在登录...");
            btnObj.prop('disabled','disabled');
            setTimeout(function () {
                btnObj.val("登录");
                btnObj.removeAttr('disabled');
            }, 3000);
            var params = {};
            var jsEncrypt = new JSEncrypt();
            jsEncrypt.setPublicKey($('#pubkey').val());
            params.username=$('#username').val();
            params.validateCode=$('#validateCode').val();
            params.password=encodeURI(jsEncrypt.encrypt($('#pubword').val())).replace(/\+/g, '%2B');
            params._csrf=$('#_csrf').val();
            $.ajax({
                url : 'loginProcesses',
                type : 'POST',
                cache: false,
                data : params,
                success: function(data) {
                    if(data!=null){
                        if(data.code == 0){
                            var returnUrl = $('#returnurl').val();
                            if (returnUrl=="" || returnUrl == undefined) {
                                returnUrl = "index";
                            }
                            window.location.href= returnUrl;
                        }else{
                            $('div.tip-box').text(data.msg);
                            $('#vcImg').attr('src','validatecode?randomStr='+randomString(6));
                        }
                    }
                },
                error: function(data){
                    $('div.tip-box').text(data.msg);
                }
            });
            return false;
        });
        
        form.on('submit(dialoglogin)', function(data){
            var btnObj = $(this);
            btnObj.val("正在登录...");
            btnObj.prop('disabled','disabled');
            setTimeout(function () {
                btnObj.val("登录");
                btnObj.removeAttr('disabled');
            }, 3000);
            var data = {};
            var jsEncrypt = new JSEncrypt();
            jsEncrypt.setPublicKey($('#pubkey').val());
            data.username = $('#username').val();
            data.password = encodeURI(jsEncrypt.encrypt($('#pubword').val())).replace(/\+/g, '%2B');
            data.validateCode = $('#validateCode').val();
            $.ajax({
                url : '${contextPath}/loginProcesses',
                type : 'POST',
                cache: false,
                data :data,
                success: function(data) {
                    if(data!=null){
                        if(data.code == 0){
                            parent.layer.close(parent.layer.getFrameIndex(window.name));
                            window.parent.location.reload();
                        }else{
                            $('div.tip-box').text(data.msg);
                        }
                    }
                },
                error: function(data){
                    $('div.tip-box').text(data.msg);
                }
            });
            return false;
        });
        
        form.on('submit(regist)',function(data){
            var btnObj = $(this);
            btnObj.val("正在注册...");
            btnObj.prop('disabled','disabled');
            setTimeout(function () {
                btnObj.val("注册");
                btnObj.removeAttr('disabled');
            }, 3000);
            var jsEncrypt = new JSEncrypt();
            jsEncrypt.setPublicKey($('#pubkey').val());
            var loginCode = $.trim($("#registmobile").val());
            var validateCode = $.trim($("#validatecode").val());
            var passWord = encodeURI(jsEncrypt.encrypt($.trim($("#password").val()))).replace(/\+/g, '%2B');
            var confirmPass = encodeURI(jsEncrypt.encrypt($.trim($("#confirmpass").val()))).replace(/\+/g, '%2B');
            var param = {"logincode": loginCode, "password":passWord, "confirmpass":confirmPass, "validatecode":validateCode};
            $.post("regist", param, function(data){
                if(data.code == '1'){
                    $('div.tip-box').text(data.msg);
                }else{
                    $('div.tip-box').text("");
                    layer.open({
                      type: 1
                      ,title: false 
                      ,closeBtn: false
                      ,area: '300px;'
                      ,btn: ['前去登录']
                      ,btnAlign: 'c'
                      ,content: '<div style="padding: 50px; line-height: 22px; background-color: #5FB878; color: #fff; align-center:center; ">'+data.msg+'</div>'
                      ,success: function(layero){
                           var btn = layero.find('.layui-layer-btn');
                           btn.find('.layui-layer-btn0').attr({
                               href: 'login'
                           });
                      }
                  });
                }
            });
        });
        
        form.on('submit(reset_email)',function(data){
            var btnObj = $(this);
            var email = $("#resetemail").val();
            if(email==""){
                $('.tip-box').text("请输入电子邮箱！");
                return false;
            }
            var vcode = $("#validatecode").val();
            if(vcode==""){
                $('.tip-box').text("请输入验证码！");
                return false;
            }
            var newPass = $("#password").val();
            if(newPass==""){
                $('.tip-box').text("请输入新密码！");
                return false;
            }
            var confirmPass = $("#confirmpass").val();
            if(confirmPass==""){
                $('.tip-box').text("请输入确认密码！");
                return false;
            }
            if(confirmPass!=newPass){
                $('.tip-box').text("两次输入的密码不一致！");
                return false;
            }
            var jsEncrypt = new JSEncrypt();
            jsEncrypt.setPublicKey($('#pubkey').val());
            newPass = encodeURI(jsEncrypt.encrypt(newPass)).replace(/\+/g, '%2B');
            confirmPass = encodeURI(jsEncrypt.encrypt(confirmPass)).replace(/\+/g, '%2B');
            btnObj.attr("disabled", true);
            btnObj.val("正在重置...");
            btnObj.prop('disabled','disabled');
            setTimeout(function () {
                btnObj.val("重置密码");
                btnObj.removeAttr('disabled');
            }, 2000);
            $.ajax({
                type : 'POST',
                async : false,
                cache : false,
                url : 'email_reset',
                data : {'emailnum' : email, 'validatecode': vcode, 'newpass': newPass,'confirmpass':confirmPass},
                success:function(data){
                    if(data.code == '0'){
                        $('div.tip-box').text("");
                        btnObj.val(data.msg);
                        setTimeout(function () { 
                            window.location.href="login";
                        }, 2000);
                    }else{
                        $('div.tip-box').text(data.msg);
                    }
                }
            });
        });
        
        form.on('submit(reset_mobile)',function(data){
            var btnObj = $(this);
            var mobile = $("#resetmobile").val();
            if(mobile==""){
                $('.tip-box').text("请输入手机号码！");
                return false;
            }
            var vcode = $("#validatecode").val();
            if(vcode==""){
                $('.tip-box').text("请输入验证码！");
                return false;
            }
            var newPass = $("#password").val();
            if(newPass==""){
                $('.tip-box').text("请输入新密码！");
                return false;
            }
            var confirmPass = $("#confirmpass").val();
            if(confirmPass==""){
                $('.tip-box').text("请输入确认密码！");
                return false;
            }
            if(confirmPass!=newPass){
                $('.tip-box').text("两次输入的密码不一致！");
                return false;
            }
            var jsEncrypt = new JSEncrypt();
            jsEncrypt.setPublicKey($('#pubkey').val());
            newPass = encodeURI(jsEncrypt.encrypt(newPass)).replace(/\+/g, '%2B');
            confirmPass = encodeURI(jsEncrypt.encrypt(confirmPass)).replace(/\+/g, '%2B');
            btnObj.attr("disabled", true);
            btnObj.val("正在重置...");
            btnObj.prop('disabled','disabled');
            setTimeout(function () {
                btnObj.val("重置密码");
                btnObj.removeAttr('disabled');
            }, 2000);
            $.ajax({
                type : 'POST',
                async : false,
                cache : false,
                url : 'mobile_reset',
                data : {'mobilenum' : mobile, 'validatecode': vcode, 'newpass': newPass,'confirmpass':confirmPass},
                success:function(data){
                    if(data.code == '0'){
                        $('div.tip-box').text("");
                        btnObj.val(data.msg);
                        setTimeout(function () { 
                            window.location.href="login";
                        }, 2000);
                    }else{
                        $('div.tip-box').text(data.msg);
                    }
                }
            });
        })
    });
})
